<?php

namespace app\common\model\xilumarket;

use app\common\library\Auth;
use app\common\model\User;
use think\db\Expression;
use think\Exception;
use think\exception\PDOException;
use think\Hook;
use think\Model;
use function fast\array_get;


class Withdraw extends Model
{

    

    

    // 表名
    protected $name = 'xilumarket_withdraw';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'state_text'
    ];
    

    
    public function getStateList()
    {
        return ['1' => __('State 1'), '2' => __('State 2'), '3' => __('State 3'), '4' => __('State 4')];
    }


    public function getStateTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['state']) ? $data['state'] : '');
        $list = $this->getStateList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function user(){
        return $this->belongsTo(User::class,'user_id','id',[],'left')->setEagerlyType(0);
    }

    /**
     * 获取提现次数
     * @param $where
     */
    public static function withdraw_count($where){
        return static::where($where)->count();
    }

    /**
     * @param array $params
     */
    public static function withdraw($params,$user){
        $config = Config::getMyConfig("apply");
        if(!$config || $config['apply_status'] != '1'){
            throw new Exception("提现未开启或未配置");
        }
        $money = array_get($params,'money');
        if($config['apply_small_money'] > $money){
            throw new Exception("低于最低提现金额");
        }
        if($config['apply_large_money'] < $money){
            throw new Exception("高于最高提现金额");
        }
        $withdraw_count = static::withdraw_count(['createtime'=>['between',[strtotime(date('Y-m-d')), strtotime(date('Y-m-d 23:59:59'))]]]);
        if($config['apply_daily_num'] <=$withdraw_count){
            throw new Exception("达到每天提现次数上限");
        }
        #判断用户余额是否充足
        $account = UserAccount::get(['user_id'=>$user->id]);
        if(!$account || $account->money<$money){
            throw new Exception("余额不足");
        }
        #添加提现记录
        $rate = $config['apply_rate']/100 ?? 0; //手续费率
        $rate_money = bcmul($rate,$money,2);
        $real_money = bcsub($money, $rate_money,2);
        unset($params['money']);
        $withdraw = array_merge([
            'order_no'  =>  'W'.date('YmdHis').mt_rand(100,9999),
            'user_id'   =>  $user->id,
            'money'     =>  $money,
            'real_money'=>  $real_money,
            'rate'      =>  $rate,
            'rate_money'=>  $rate_money,
            'state'     =>  '1'
        ],$params);
        static::startTrans();
        try {
            $result = self::create($withdraw);
            $account->money = new Expression("money-".$money);
            $account->save();
            Hook::listen("xilumarket_withdraw",$result);
        }catch (Exception|PDOException $e){
            static::rollback();
            throw $e;
        }
        static::commit();
        return $result;
    }

    /**
     * 获取用提现记录
     */
    public static function get_withdraw($params){
        $auth = Auth::instance();
        $user_id = $auth->id;
        $tab = $params['tab'] ?? 'checking';
        $pagesize = $params['pagesize'] ?? 10;
        switch($tab){
            case 'checking':
                #审核中
                $where['state'] = ['in',['1','2']];
                $order = 'createtime desc';
                break;
            case "check_ok":
                #成功
                $where['state'] = '3';
                $order = 'updatetime desc';
                break;
            default:
                #拒绝
                $where['use_status'] = '4';
                $order = 'updatetime asc';
        }

        return static::where('user_id',$user_id)
            ->where($where)
            ->order($order)
            ->paginate($pagesize);
    }

}
